from typing import Optional
from langchain_core.language_models import BaseChatModel
from langchain_core.tools import BaseTool
from typing import List

from app.services.tools.agent import ToolAgent
from app.services.tools.toolkit import get_available_tools
from app.services.llm.deepseek_service import DeepseekChatModel
from app.config.settings import settings


class AgentManager:
    """Agent管理器 - 饿汉单例模式"""
    
    _instance = None
    _agent: Optional[ToolAgent] = None
    _llm: Optional[BaseChatModel] = None
    
    # 类加载时立即初始化实例
    def __new__(cls) -> 'AgentManager':
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            # 初始化LLM和Agent
            cls._llm = DeepseekChatModel(
                api_key=settings.DEEPSEEK_API_KEY,
                api_base=settings.DEEPSEEK_API_BASE,
                model_name=settings.DEEPSEEK_MODEL,
                streaming=True,
                temperature=0.7,
            )
            cls._agent = ToolAgent(llm=cls._llm, tools=get_available_tools())
        return cls._instance
    
    @classmethod
    def get_llm(cls) -> BaseChatModel:
        """获取LLM实例"""
        return cls._llm
    
    @classmethod
    def get_agent(cls) -> ToolAgent:
        """获取Agent实例"""
        return cls._agent
    
    @classmethod
    def reset_agent(cls):
        """重置Agent实例"""
        cls._agent = ToolAgent(llm=cls._llm, tools=get_available_tools())


# 全局实例
agent_manager = AgentManager()


def get_singleton_agent() -> ToolAgent:
    """获取单例Agent实例"""
    return agent_manager.get_agent()


def get_singleton_llm() -> BaseChatModel:
    """获取单例LLM实例"""
    return agent_manager.get_llm()